﻿using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace Se.Framework.Common.Config.Urls
{
    [Serializable]
    public class ServicesConfiguration
    {
        public ServicesConfiguration()
        {
            Services = new Collection<ServiceUrlBuilder>();
        }

        [XmlArray]
        public Collection<ServiceUrlBuilder> Services { get; set; }

        #region Static Methods

        public static ServicesConfiguration LoadFromConfigFile()
        {
            var configValue = ConfigurationManager.AppSettings["ServicesConfig"];
            if (configValue != null)
            {
                if (Path.IsPathRooted(configValue))
                {
                    return LoadFromFile(configValue);
                }
                string path = Assembly.GetExecutingAssembly().CodeBase.Remove(0, 8).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                path = path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar));
                return LoadFromFile(Path.Combine(path, configValue));
            }

            return null;
        }

        public static ServicesConfiguration LoadFromFile(string filePath)
        {
            using (var file = XmlReader.Create(filePath))
            {
                var result = LoadFromXml(file);
                return result;
            }
        }

        public static ServicesConfiguration LoadFromXml(XmlReader reader)
        {
            try
            {
                using (reader)
                {
                    XmlSerializer ser = new XmlSerializer(typeof(ServicesConfiguration));
                    return (ServicesConfiguration)ser.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Services Configuration error: {0}", ex);
            }

            return null;
        }

        #endregion Static Methods
    }
}